const query = window.location.search;
const searchObj = Qs.parse(query ? query.substring(1) : null);
// 当前日期
const today = moment().startOf('day');
// 当前时间
const hour = moment().hour();
// 获取当前时间描述
const getHourDes = () => {
  if (hour >= 0 && hour < 8) {
    return '凌晨';
  } else if (hour >= 8 && hour < 12){
    return '上午';
  }else if (hour >= 12 && hour < 14){
    return '中午';
  }else if (hour >= 14 && hour < 18){
    return '下午';
  }else if (hour >= 18 && hour < 24){
    return '晚上';
  }
}
// 默认文案
const getDefaultText = () =>
`${getHourDes()}好！亲爱的老婆。`;
// 日期提醒
const getTodayText = () => {
  const todayStr = today.format("yyyy年MM月DD日");
  const days = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ][today.days()];
// 天气概述
const wl = searchObj.wl ? searchObj.wl.split("_") : [];
const [currentWl = '', ...wl10] = wl;
const [tomorrow] = wl10;
const wendu = parseInt(currentWl);
const tqzk = currentWl.replace(`${wendu}`, "");
const isYu = wl10.every((v) => !v.includes("雨"));
const tomorrowwendu = parseInt(tomorrow);
const tomorrowtqzk = tomorrow.replace(`${tomorrowwendu}`, "");
return `今天是${todayStr}，${days}。天气平均温度为${wendu}度，天气状况：${tqzk}。\n 明天气温${tomorrowwendu}度，${tomorrowtqzk}。并且，未来十天内${
  isYu ? "无" : "有"
}雨`;
};

/**
 * 天气预报
 * 0%-20% 几乎不会降雨
 * 30% ─50% 可能会降雨
 * 60%─ 70% 很大可能会降雨
 * 80% - 100% 会降雨
 * 
 * 上午：08:00:00 - 12:00:00

中午：12:00:01 - 13:59:59

下午：14:00:00 - 18:00:00

晚上：18:00:01 - 24:00:00
 */
// 获取一天时间的平均值
const formatSearch = (searchStr) => {
  if(!searchStr) return;
  let searchArr = searchStr.split("_");
  searchArr = Array((hour || 1)  - 1).fill(null).concat(searchArr);
  // 上午平均值
  const morning =
    searchArr.slice(8, 13).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 5;
  const noon =
    searchArr.slice(12, 15).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 3;
  const afternoon =
    searchArr.slice(14, 19).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 5;
  const night =
    searchArr.slice(18, 25).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 7;
  return { morning, noon, afternoon, night };
};
formatSearch('3.11_1.74_2.4_3.08_3.52_5.5_6.76_7.54_6.42_5.5_5.23_5.58_5.8_5.7_5.68_5.68_5.68_5.39_5.54_5.26_5.16_5.07_4.76_4.23_4.06')
// 防晒提醒
const fangshai = () => {
  if (!searchObj)
    return "今天天气怎么样呢？希望善变的天气不会影响你一天的好心情呦。";
  let { ziwaix } = searchObj;
  ziwaix = parseInt(ziwaix);
  switch (ziwaix) {
    case 0:
    case 1:
    case 2:
      return "今天可以不用涂防晒霜啦！是不是不用担心卡粉了？";
    case 3:
    case 4:
      return "外出记得涂抹防晒霜哦";
    default:
      return "呆在家里吧，防晒霜都没有。";
  }
};
const getTodayWeather = () => {
  if (!searchObj)
    return "今天天气怎么样呢？希望善变的天气不会影响你一天的好心情呦。";
  // 天气概况 最低气温提醒是否需要添加衣物  体感温度提醒是否温度适宜
  let { fs, jsgl, wd, zwx } = searchObj;
  wd = formatSearch(wd);
  fs = formatSearch(fs);
  jsgl = formatSearch(jsgl);
  zwx = formatSearch(zwx);
  // 温度
  const wdF = ({ morning, noon, afternoon, night }) => {
    if (
      morning >= 17 &&
      morning <= 24 &&
      noon >= 17 &&
      noon <= 24 &&
      afternoon >= 17 &&
      afternoon <= 24 &&
      night >= 17 &&
      night <= 24
    ) {
      return "今天气温一天都很棒。";
    } else if (afternoon < 5) {
      return "今天气温有点冷，记得多穿点衣服。";
    } else if (afternoon < 17) {
      return "今天天气微凉，记得穿外套呢。";
    } else if (
      afternoon >= 17 &&
      afternoon <= 24 &&
      (morning > 15 || night > 15)
    ) {
      return "今天气温不错呦。";
    } else if (
      afternoon >= 17 &&
      afternoon <= 24 &&
      (morning < 15 || night < 15)
    ) {
      return "今天早上和晚上的气温还是有点低，不过中午的气温不错呢。";
    } else if (night >= 17 && night <= 24 && afternoon < 30) {
      return "今天早上和晚上的气温不错，中午有点点热。";
    } else if (night >= 17 && night <= 24 && afternoon > 30) {
      return "今天早上和晚上的气温不错，中午有非常热。";
    } else if (night > 24 && afternoon > 30) {
      return "今天一天都很热。";
    } else {
      return `今天上午气温${morning}，中午气温：${noon}，下午气温：${afternoon}，晚上气温：${night}。`;
    }
  };
  // 降雨
  const jsF = ({ morning, noon, afternoon, night }) => {
    if (morning < 0.2 && noon < 0.2 && afternoon < 0.2 && night < 0.2) {
      // 无雨
      return "今天不会下雨哦，";
    } else {
      let str = "";
      if (morning <= 0.2) {
      } else if (morning < 0.4) {
        str += "早上可能会下雨";
      } else {
        str += "今天的雨";
      }


      if (noon <= 0.2) {
        if (str) {
          str += "将会在中午停下来";
        }
      } else if (noon < 0.4) {
        !str && (str += "中午可能会下雨");
      } else {
        if (str.includes('可能')) {
          str += '中午必定会下雨'
        } 
        !str && (str += "中午的雨");
      }


      if (afternoon <= 0.2) {
        if (str && !str.endsWith("停下来")) {
          str += "将会在下午停下来";
        }
      } else if (afternoon < 0.4) {
        
        !str && (str += "下午可能会下雨");
      } else {
        if (str.includes('可能') && !str.includes('必定')) {
          str += '下午必定会下雨'
        } 
        if (!str) {
          str += "下午的雨";
        } else {
          if (str.endsWith("停下来")) {
            str += "下午又下起来了";
          } else if (str.includes("的雨") || str.includes("可能") || str.includes("必定")) {
            str += "";
          } else {
          }
        }
      }


      if (night <= 0.2) {
        if (str && !str.endsWith("停下来")) {
          str += "将会在晚上停下来";
        }
      } else if (night < 0.4) {
        !str && (str += "晚上可能会下雨");
      } else {
        if (!str) {
          str += "晚上会下雨";
        } else {
          if (str.includes('可能') && !str.includes('必定')) {
            str += '晚上必定会下雨'
          } else if (str.endsWith("停下来")) {
            str += "晚上又下起来了";
          } else if (str.includes("的雨") || str.includes("可能") || str.includes("必定")) {
            str += "晚上也不会停";
          }
        }
      }
      return str ? `下雨影响好心情了吗？${str}。` : "";
    }
  };

  // 紫外线
  const zwxF = ({ morning, noon, afternoon, night }) => {
    if (morning < 2 && noon < 2 && afternoon < 2 && night < 2) {
      return "紫外线也并不高哦，可以不用涂抹防晒霜。";
    } else if (noon > 3 && afternoon > 3 && morning > 3 && night > 3) {
      return "一天的紫外线都很高，呆在家里吧，涂防晒霜都没有用。";
    } else {
      return `部分时间的紫外线还是有点高呢，出门记得涂点防晒霜哦。`;
    }
  };

  // 风速

  const fsF = ({ morning, noon, afternoon, night }) => {
    // 换算单位
    morning = Number(((morning * 1000) / 3600).toFixed(2));
    noon = Number(((noon * 1000) / 3600).toFixed(2));
    afternoon = Number(((afternoon * 1000) / 3600).toFixed(2));
    night = Number(((night * 1000) / 3600).toFixed(2));
    const feng = [morning, noon, afternoon, night];
    if (feng.every((v) => v < 3.3)) {
      return "无风";
    } else if (feng.every((v) => v < 5)) {
      return "微风";
    } else if (feng.every((v) => v < 9)) {
      return "今天有大风，注意扬尘。";
    } else if (feng.every((v) => v < 13)) {
      return "今天有强风，呆在家里吧，皓雪可能会被刮跑。";
    } else {
      return "今天有飓风，呆在家里吧，你和皓雪都会被刮跑";
    }
  };
  return `${wdF(wd)}${jsF(jsgl)}${zwxF(zwx)}${fsF(fs)}`;
};
// 一共多少日子
const getTotalDay = () => {
  const diffDay = today.diff("2018-02-22", "d");
  return `在我们相识的${diffDay}天里，生活的柴米油盐，日子的酸甜苦辣。有过浪漫，有吵有闹。最后我们还是我们，是走向幸福的那群人，让我们一起慢慢变老。`;
};
// 纪念日
const jinianriStr = () => {
  const jinianri = [
    {
      date: "2018-02-22",
      dateType: "公历",
      dateUse: "meet",
      dateUser: "wife",
      des: "相识纪念日",
    },
    {
      date: "2019-10-01",
      dateType: "公历",
      dateUse: "marry",
      dateUser: "wife",
      des: "结婚纪念日",
    },
    {
      date: "1992-04-13",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "wife",
      des: "亲亲你爸生日",
    },
    {
      date: "1962-04-17",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "wife",
      des: "亲亲我爸生日",
    },
    {
      date: "1963-07-11",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "wife",
      des: "亲亲我妈生日",
    },
    {
      date: "1992-03-20",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "wife",
      des: "亲亲老婆生日",
    },
    {
      date: "2020-05-27",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "child",
      des: "皓雪生日",
    },
    {
      date: "2024-09-23",
      dateType: "公历",
      dateUse: "EDC",
      dateUser: "child",
      des: "预产期",
    },
  ];
  // 获取日子还有多少天
  const getBir = (m, d, type = "公历", dateUse = 'birthday') => {
    // 判断今年的农历是否过去了
  const year = today.year();
    let gongli = `${year}-${m}-${d}`;
    if (type !== "公历") {
      // 农历转公历
      gongli = chineseLunar.lunarToSolar(year, +m, +d);
    }
    let dd = today.diff(gongli, "d");
    if (dd > 0 && dateUse !== '纪念日') {
      // 加一年
      if (type !== "公历") {
        gongli = chineseLunar.lunarToSolar(year + 1, +m, +d);
      } else {
        gongli = `${year + 1}-${m}-${d}`;
      }
      dd = today.diff(gongli, "d");
    }
    return  dateUse !== '纪念日' ? -dd : dd;
  };

  return jinianri.reduce((sum, item, index) => {
    const { date, dateType, des, dateUse, dateUser } = item;
    const [y, m, d] = date.split("-");
    let tips = "";
    if (dateUse === 'EDC') {
      /** 预产期 **/

      tips = `预产期是：${date}, 距今还有：${moment(date).diff(today, 'd')}天`
    } else {
      const countDate = getBir(m, d, dateType, dateUse);
      
      let birthdayTips = "";
      if (dateUse === "birthday" && dateUser === "child") {
        let dateCopy = date;
        if (dateType === '农历') {
          dateCopy = chineseLunar.lunarToSolar(+y, +m, +d)
        }
        const diffD = today.diff(dateCopy, "y") + 1;
        birthdayTips = diffD + "岁";
      }
      if (countDate === 0) {
        tips = "今天是" + birthdayTips + des;
      } else {
        tips = `距离${dateUse === '纪念日' ? '曾' : ''}${birthdayTips}${des}${dateUse === '纪念日' ? '已经过了' : '还有'}${countDate}天。${dateUse === '纪念日' ? '' : ''}`;
      }
    }
   
    return sum + tips + (index === jinianri.length - 1 ? "" : "\n");
  }, "").split('\n').sort((a, b) => {
    if (a.startsWith('预产期')) {
      return -1
    }
    const numA = a.match(/\d+/g) || [0];
    const numB = b.match(/\d+/g) || [0];
    return numA[numA.length - 1] - numB[numB.length -1]
  }).join('\n');
};

// 获取最近节假日信息
// const getHoliday = () => {
//   // https://timor.tech/api/holiday/next
//   return new Promise((resolve) => {
//     try {
//       fetch("https://timor.tech/api/holiday/next").then((res) => {
//         res.json().then((resJ) => {
//           const {
//             holiday: { date, name, rest },
//           } = resJ;
//           resolve(
//             `还有${rest}天，我们将迎来今年的${name}，具体时间是：${date}`
//           );
//         });
//       });
//     } catch {
//       resolve(null);
//     }
//   });
// };

// Promise.all([getHoliday()]).then(([holiday]) => {
//   document.body.innerText = `
//     ${getDefaultText() /** 开场白 */}

//     ${getTodayText()}

//     【今天天气】：
//     ${getTodayWeather() /** 天气描述 */}
//     【倒计时】：
//     ${jinianriStr() /**纪念日 */}
//     【节假日】：
//     ${holiday}

//     ${getTotalDay() /** 总天数描述 */}
// `;
// });
const getHoliday = () => {
  let { jieri } = searchObj;
  if (!jieri) return "";
  jieri = JSON.parse(jieri);
  const {
    holiday: { date, name, rest },
  } = jieri;
  return `还有${rest}天，我们将迎来今年的${name}，具体时间是：${date}`;
};

document.body.innerText = `
${getDefaultText() /** 开场白 */}
  
${getTodayText()}

【今天气温提醒】：
${getTodayWeather() /** 天气描述 */}

【倒计时】：
${jinianriStr() /**纪念日 */}

【节假日】：
${getHoliday() || '暂无节假日信息' /**节假日 */}

${getTotalDay() /** 总天数描述 */}
`;
